<template>
  <div class="DataBoard_container main_container">
    <div v-if="isPictrue==1" class="imgDiv" :style="{backgroundImage: 'url(' + fileUrl + ')'}">
      <div v-for="(item,index) in displayStr" :key="index">
        {{ item }}
      </div>
    </div>
    <div v-else>
      <div class="main_headers">
        <div class="title">{{ name }}</div>
        <div style="width:800px">
          <NoticeText :sends-val="textData" />
        </div>
        <div class="data">
          <div v-if="temperature" style="margin-right:60px">温度:{{ temperature }}°C</div>
          <div v-if="humidity" style="margin-right:60px">湿度:{{ humidity }}%</div>
          <div style="width:210px;">{{ nowDate }}</div>
          <div>{{ '周' + '日一二三四五六'.charAt(new Date().getDay()) }}</div>
        </div>
      </div>
      <div class="DataBoard_container_main">
        <div class="DataBoard_container_main_statistics">
          <div
            v-for="(item, index) in showStatisticsItem"
            :key="index"
            class="statistics_item"
          >
            <div
              class="statistics_item_icon"
              :style="{ backgroundColor: item.bgColor }"
            >
              <svg-icon :icon-class="item.icon" />
            </div>
            <div class="statistics_item_number">
              {{ statisticsData[item.dataKey] }}
            </div>
            <div class="statistics_item_background1" />
            <div class="statistics_item_background" />
            <div class="statistics_item_name">{{ item.name }}</div>
          </div>
        </div>
        <div class="DataBoard_container_main_charts">
          <div
            v-for="(item, index) in showChartItem.filter(
              (item) =>
                item.component&&item.isShow != '0'
            )"
            :key="index"
            class="charts_item"
            :class="item.length ? 'double' : ''"
          >
            <EquipmentStatusTodays v-if="item.component == 'EquipmentStatusTodays'" />
            <AlarmInformation v-if="item.component == 'AlarmInformation'" />
            <DetailInspectedToday v-if="item.component == 'DetailInspectedToday'" />
            <OEESequenceDiagram v-if="item.component == 'OEESequenceDiagram'" :target-number="OEENumber" />
            <OnDutyPersonnel v-if="item.component=='OnDutyPersonnel'" />
            <CapacityStatistics v-if="item.component == 'CapacityStatistics'" :target-number="capacityNumber" />
            <EquipmentPower v-if="item.component == 'EquipmentPower'" :device-ids="item.deviceIds" />
            <EquipmentStatusStatistic v-if="item.component == 'EquipmentStatusStatistic'" :device-ids="item.deviceIds" />
            <checkPlanFinishedRate v-if="item.component == 'checkPlanFinishedRate'" />
            <RankingFaultTimes v-if="item.component == 'RankingFaultTimes'" />
            <WorkshopEquipmentRealTime v-if="item.component == 'WorkshopEquipmentRealTime'" />
            <EquipmentUtilization v-if="item.component == 'EquipmentUtilization'" />
            <TaskStatistics v-if="item.component=='TaskStatistics'" />
            <DetailsMaintainMonth v-if="item.component=='DetailsMaintainMonth'" />
            <OverdueWorkOrder v-if="item.component=='OverdueWorkOrder'" />
            <WorkOrderDetailsInRepair v-if="item.component=='WorkOrderDetailsInRepair'" />

            <LocationDistribution v-if="item.component=='LocationDistribution'" />
            <MaintainPlanTimelinessRate v-if="item.component=='MaintainPlanTimelinessRate'" />
            <RepairTypeDistribution v-if="item.component=='RepairTypeDistribution'" />
            <DegreeDistribution v-if="item.component=='DegreeDistribution'" />
            <MaintenanceCostStatistics v-if="item.component=='MaintenanceCostStatistics'" />
            <MachineHaltDuration v-if="item.component=='MachineHaltDuration'" />
            <SparePartsConsumptionRanking v-if="item.component=='SparePartsConsumptionRanking'" />
            <PowerDistribution v-if="item.component=='PowerDistribution'" />
            <ElectricityYearOnYear v-if="item.component=='ElectricityYearOnYear'" />
            <MaintenanceHoursThisMonth v-if="item.component=='MaintenanceHoursThisMonth'" />
            <DailyElectricity v-if="item.component=='DailyElectricity'" :threshold="item.threshold" />
            <!-- 销售看板 -->
            <MaterialSalesRanking v-if="item.component=='MaterialSalesRanking'" />
            <saleSendWarning v-if="item.component=='saleSendWarning'" />
            <TimelyDeliveryRate v-if="item.component == 'TimelyDeliveryRate'" :target-number="deliveryNumber" />
            <!-- 采购看板 -->
            <purchaseDeliveryTimeWarning v-if="item.component=='purchaseDeliveryTimeWarning'" />
            <materialPurchaseSort v-if="item.component=='materialPurchaseSort'" />
            <consignmentTimely v-if="item.component=='consignmentTimely'" :target-number="consignmentNumber" />
            <!-- 仓库看板 -->
            <WarehouseInventoryProportion v-if="item.component=='WarehouseInventoryProportion'" />
            <MaterialClassificationInventory v-if="item.component=='MaterialClassificationInventory'" />
            <OverstockedMaterials v-if="item.component=='OverstockedMaterials'" />
            <LowstockedMaterials v-if="item.component=='LowstockedMaterials'" />
            <InboundOutboundNotifications v-if="item.component=='InboundOutboundNotifications'" :notice="noticeNumber" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { deviceHeadDate } from '@/api/equipmentManage/equipmentReport/dataBoard' // 接口
import { getInfoByCode, getLargeScreenVersion } from '@/api/system/largeScreenDetail' // 接口
import { temperature } from '@/api/system/largeScreen'
import NoticeText from './components/text.vue'
import EquipmentStatusTodays from './components/EquipmentStatusTodays.vue'
import AlarmInformation from './components/AlarmInformation.vue'
import OEESequenceDiagram from './components/OEESequenceDiagram.vue'
import OnDutyPersonnel from './components/OnDutyPersonnel.vue'
import CapacityStatistics from './components/CapacityStatistics.vue'
import checkPlanFinishedRate from './components/checkPlanFinishedRate.vue'
import RankingFaultTimes from './components/RankingFaultTimes.vue'
import WorkshopEquipmentRealTime from './components/WorkshopEquipmentRealTime.vue'
import TaskStatistics from '../../equipmentManage/equipmentReport/dataBoard/components/TaskStatistics.vue'
import EquipmentUtilization from './components/EquipmentUtilization.vue'
import DetailInspectedToday from './components/DetailInspectedToday.vue'
import DetailsMaintainMonth from './components/DetailsMaintainMonth.vue'
import OverdueWorkOrder from './components/OverdueWorkOrder.vue'
import EquipmentPower from './components/EquipmentPower.vue' // 设备功率
import PowerDistribution from './components/PowerDistribution.vue' // 峰平谷电量
import ElectricityYearOnYear from './components/ElectricityYearOnYear.vue' // 电量同比分析
import DailyElectricity from './components/DailyElectricity.vue' // 日用电量趋势
import EquipmentStatusStatistic from './components/EquipmentStatusStatistic.vue' // 今日设备状态
import WorkOrderDetailsInRepair from './components/WorkOrderDetailsInRepair.vue'
import LocationDistribution from '../../equipmentManage/equipmentReport/dataBoard/components/LocationDistribution.vue'
import MaintainPlanTimelinessRate from '../../equipmentManage/equipmentReport/dataBoard/components/MaintainPlanTimelinessRate.vue'
import RepairTypeDistribution from '../../equipmentManage/equipmentReport/dataBoard/components/RepairTypeDistribution.vue'
import DegreeDistribution from '../../equipmentManage/equipmentReport/dataBoard/components/EmergencyDegreeDistribution'
import MaintenanceCostStatistics from '../../equipmentManage/equipmentReport/dataBoard/components/MaintenanceCostStatistics.vue'
import MachineHaltDuration from '../../equipmentManage/equipmentReport/dataBoard/components/MachineHaltDuration.vue'
import SparePartsConsumptionRanking from '../../equipmentManage/equipmentReport/dataBoard/components/SparePartsConsumptionRanking.vue'
import MaintenanceHoursThisMonth from './components/MaintenanceHoursThisMonth.vue'
import TimelyDeliveryRate from '@/views/saleManage/saleReport/saleBoard/components/TimelyDeliveryRate.vue'
import MaterialSalesRanking from '@/views/saleManage/saleReport/saleBoard/components/MaterialSalesRanking.vue'
import saleSendWarning from '@/views/saleManage/saleReport/saleBoard/components/saleSendWarning.vue'
import purchaseDeliveryTimeWarning from '@/views/purchaseManage/purchaseStatistics/purchaseBoard/components/purchaseDeliveryTimeWarning.vue'
import materialPurchaseSort from '@/views/purchaseManage/purchaseStatistics/purchaseBoard/components/materialPurchaseSort.vue'
import consignmentTimely from '@/views/purchaseManage/purchaseStatistics/purchaseBoard/components/consignmentTimely.vue'
import WarehouseInventoryProportion from '@/views/warehouseManagement/warehouseReport/warehouseSignage/components/WarehouseInventoryProportion.vue'
import MaterialClassificationInventory from '@/views/warehouseManagement/warehouseReport/warehouseSignage/components/MaterialClassificationInventory.vue'
import OverstockedMaterials from '@/views/warehouseManagement/warehouseReport/warehouseSignage/components/OverstockedMaterials.vue'
import LowstockedMaterials from '@/views/warehouseManagement/warehouseReport/warehouseSignage/components/LowstockedMaterials.vue'
import InboundOutboundNotifications from '@/views/warehouseManagement/warehouseReport/warehouseSignage/components/InboundOutboundNotifications.vue'
import Setup from './components/Setup'
import { getPageSettings } from '@/api/common/common'
import { mapGetters } from 'vuex'
import moment from 'moment'
import defaultSettings from '@/settings'
import CryptoJS from 'crypto-js'
export default {
  name: 'DataBoard',
  components: {
    NoticeText,
    LocationDistribution,
    MaintainPlanTimelinessRate,
    RepairTypeDistribution,
    DegreeDistribution,
    MaintenanceCostStatistics,
    MachineHaltDuration,
    SparePartsConsumptionRanking,
    EquipmentStatusTodays,
    AlarmInformation,
    OEESequenceDiagram,
    OnDutyPersonnel,
    CapacityStatistics,
    checkPlanFinishedRate,
    RankingFaultTimes,
    WorkshopEquipmentRealTime,
    TaskStatistics,
    EquipmentUtilization,
    DetailInspectedToday,
    DetailsMaintainMonth,
    OverdueWorkOrder,
    WorkOrderDetailsInRepair,
    EquipmentPower,
    PowerDistribution,
    ElectricityYearOnYear,
    DailyElectricity,
    EquipmentStatusStatistic,
    MaintenanceHoursThisMonth,
    MaterialSalesRanking,
    saleSendWarning,
    TimelyDeliveryRate,
    purchaseDeliveryTimeWarning,
    materialPurchaseSort,
    consignmentTimely,
    WarehouseInventoryProportion,
    MaterialClassificationInventory,
    OverstockedMaterials,
    LowstockedMaterials,
    InboundOutboundNotifications
  }, // 组件注册
  computed: {
    ...mapGetters(['userId'])
  },
  data() {
    return {
      textData: [
        {
          name: '张三4',
          detail:
            '信息公告：2020年8月31有限公司成立，我行用信金额444444元'
        }
      ],
      temperature: '',
      timer: undefined,
      timer2: undefined,
      humidity: '',
      id: '',
      nowDate: '',
      name: '',
      OEENumber: 100,
      capacityNumber: 100,
      deliveryNumber: 60,
      consignmentNumber: 60,
      noticeNumber: 24,
      isPictrue: undefined,
      fileUrl: '',
      displayStr: [],
      statisticsItem: [
        // 可选的统计数据项
        {
          name: '设备总数',
          icon: '设备总数',
          dataKey: 'deviceTotalNumber',
          bgColor: '#FF9292'
        },
        {
          name: '今日点检（含待点检）',
          icon: '今日待点检',
          dataKey: 'waitCheckNumber',
          bgColor: '#FFC9FB4D'
        },
        {
          name: '本月待保养',
          icon: '本月待保养',
          dataKey: 'waitMaintainNumber',
          bgColor: '#D3C9FF4D'
        },
        {
          name: '维修中设备数',
          icon: '维修中设备数',
          dataKey: 'repairNumber',
          bgColor: '#FFEBC94D'
        },
        {
          name: '安全库存报警',
          icon: '安全库存报警',
          dataKey: 'safetyStockAlarm',
          bgColor: '#C9FFE14D'
        },
        {
          name: '今日点检逾期数',
          icon: '今日点检超期数',
          dataKey: 'overdueCheckNumber',
          bgColor: '#C9EEFF4D'
        },
        {
          name: '备件待盘点工单',
          icon: '待盘点工单',
          dataKey: 'waitSpareCheckNumber',
          bgColor: '#B1FCFF4D'
        },
        {
          name: '维修工单',
          icon: '维修中工单',
          dataKey: 'repairRecordNumber',
          bgColor: '#F7FFC94D'
        },
        {
          name: '本月维修工时(h)',
          icon: '本月维修工时',
          dataKey: 'monthRepairTime',
          bgColor: '#76FFFE'
        }
      ],
      chartItem: [
        // 可选的图表项
        { name: '设备紧急程度分布', component: 'DegreeDistribution' },
        { name: '点检计划完成率', component: 'CheckPlanCompletedRatio' },
        { name: '维修费用统计', component: 'MaintenanceCostStatistics' },
        { name: '备件消耗排行', component: 'SparePartsConsumptionRanking' },
        { name: '设备位置分布', component: 'LocationDistribution' },
        { name: '保养计划及时率', component: 'MaintainPlanTimelinessRate' },
        // { name: '停机时间排行', component: 'MachineHaltDuration' },
        { name: '故障类型分布', component: 'RepairTypeDistribution' },
        { name: '任务统计', component: 'TaskStatistics', length: '2' }
      ],
      statisticsData: {},
      pageId: '设备数据看板',
      showStatisticsItem: [], // 真正展示的统计数据项
      showChartItem: [], // 真正展示的图表项
      companyId: '',
      largeScreenJson: {}, // 保存大屏相关信息
      largeScreenVersion: '' // 大屏版本（变动之后自动刷新页面）
    }
  },
  created() {
    const json = JSON.parse(this.decrypt(this.$route.query.key, defaultSettings.aesKey))
    this.largeScreenJson = json
    this.$store.commit('user/SET_companyId', json.companyId)
    this.$store.commit('user/SET_USERID', json.userId)
    this.getInfoByCode(json)
  },
  mounted() {
    // this.getPageSettings()
    this.getStatisticsData()
    this.timer = setInterval(() => {
      this.getStatisticsData()
    }, this.$store.state.common.refreshFrequency * 1000)
    this.getTemperature()
    setInterval(() => {
      this.nowDate = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    }, 1000)
    this.getLargeScreenVersionFirst()
    this.timer2 = setInterval(() => {
      this.getLargeScreenVersion() // 每 60 秒拿一次大屏版本，发生变动后自动刷新页面
    }, 60 * 1000)
  },
  beforeDestroy() {
    clearInterval(this.timer)
    clearInterval(this.timer2)
  },
  methods: {
    getLargeScreenVersionFirst() { // 拿一次大屏版本
      getLargeScreenVersion(this.largeScreenJson.companyId, this.largeScreenJson.code).then(res => {
        this.largeScreenVersion = res.data
      })
    },
    getLargeScreenVersion() { // 获取大屏版本，用来自动刷新
      getLargeScreenVersion(this.largeScreenJson.companyId, this.largeScreenJson.code).then(res => {
        if (res.data && this.largeScreenVersion != res.data) {
          location.reload()
        }
      })
    },

    resetScale() {
      const scaleX = document.documentElement.clientWidth / 1920
      const scaleY = document.documentElement.clientHeight / 1080

      document.getElementsByTagName('body')[0].style.transform = 'scale(' + scaleX + ', ' + scaleY + ')'
      document.getElementsByTagName('body')[0].style.transformOrigin = 'left top'
      document.getElementsByTagName('body')[0].style.marginRight = -(1920 * (1 - scaleX)) + 'px'
      document.getElementsByTagName('body')[0].style.marginBottom = -(1080 * (1 - scaleY)) + 'px'

      document.getElementsByTagName('body')[0].style.width = 'auto'
      document.getElementsByTagName('body')[0].style.height = 'auto'
    },
    // 获取顶部统计数据
    getStatisticsData() {
      deviceHeadDate().then((res) => {
        this.statisticsData = res.data
      })
    },
    getTemperature() {
      temperature({ companyId: this.$store.state.user.companyId }).then(res => {
        this.humidity = res.data.humidity
        this.temperature = res.data.temperature
      })
    },
    getInfoByCode(code) {
      getInfoByCode(code).then(res => {
        this.isPictrue = res.data.displayContent
        this.fileUrl = res.data.fileUrl || ''
        if (this.isPictrue == 1) {
          this.displayStr = res.data.displayStr.split(/[(\r\n)\r\n]+/)
          // 删除空项
          this.displayStr.forEach((item, index) => {
            if (!item) {
              this.displayStr.splice(index, 1)
            }
          })
        }

        this.showStatisticsItem = JSON.parse(res.data.statistical)
        this.showChartItem = JSON.parse(res.data.chart)
        if (this.showChartItem.filter(item => item.component == 'OEESequenceDiagram').length > 0) {
          this.OEENumber = Number(this.showChartItem.filter(item => item.component == 'OEESequenceDiagram')[0].number)
        }
        if (this.showChartItem.filter(item => item.component == 'CapacityStatistics').length > 0) {
          this.capacityNumber = Number(this.showChartItem.filter(item => item.component == 'CapacityStatistics')[0].number)
        }
        if (this.showChartItem.filter(item => item.component == 'TimelyDeliveryRate').length > 0) {
          this.deliveryNumber = Number(this.showChartItem.filter(item => item.component == 'TimelyDeliveryRate')[0].number)
        }
        if (this.showChartItem.filter(item => item.component == 'consignmentTimely').length > 0) {
          this.consignmentNumber = Number(this.showChartItem.filter(item => item.component == 'consignmentTimely')[0].number)
        }
        if (this.showChartItem.filter(item => item.component == 'InboundOutboundNotifications').length > 0) {
          this.noticeNumber = Number(this.showChartItem.filter(item => item.component == 'InboundOutboundNotifications')[0].notice)
        }
        this.name = res.data.name
        this.$store.state.common.refreshFrequency = res.data.refreshFrequency
        this.$nextTick(() => {
          if (this.isPictrue == 2) {
            this.resetScale() // 重置缩放
          }
        })
      })
    },
    // 设置
    setup() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: Setup, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            settingData: {
              StatisticsItem: this.showStatisticsItem, // 显示设置的数据
              ChartItem: this.showChartItem, // 字段搜索的数据
              id: this.id,
              pageId: this.pageId // 页面唯一标识
            }
          } // props
        },
        area: ['660px', '800px'],
        title: '看板设置', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    getPageSettings() {
      getPageSettings({ userId: this.userId, pageId: this.pageId }).then(
        (res) => {
          if (res.data.json) {
            const pageSetings = res.data.json

            this.showStatisticsItem = pageSetings.StatisticsItem
            this.showChartItem = pageSetings.ChartItem

            this.id = res.data.id
          } else {
            this.showStatisticsItem = this.$deepClone(this.statisticsItem)
            this.showChartItem = this.$deepClone(this.chartItem)
          }
        }
      )
    },
    // aes解密
    decrypt(word, keyStr) {
      keyStr = keyStr || 'absoietlj32fai12'
      var key = CryptoJS.enc.Utf8.parse(keyStr)
      var decrypt = CryptoJS.AES.decrypt(word, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
      return CryptoJS.enc.Utf8.stringify(decrypt).toString()
    }
  }
}
</script>

<style lang="less" scoped>
.imgDiv{
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  // background: url("~@/assets/bg.jpg");
  background-position: center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  object-fit: cover;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 80px;
  font-family: 800;
  color: white;
  padding: 0 240px;
  text-shadow:2px 2px 10px #333;
  div{
    text-align: center;
  }
}
.DataBoard_container {
  //box-shadow: inset 0px 0px 12px 0px rgba(29, 65, 134, 0.18);
  background-color: #f7f8fa;
  //background-color: #5a5e66;
  overflow-y: auto;
  .main_headers {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    background: #ffffff;
    padding: 13px 30px;
    .title {
      font-family: AlibabaPuHuiTi_2_95_ExtraBold;
      font-size: 24px;
      font-weight: 800;
      color: #333333;
      max-width: 400px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .data {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      font-family: AlibabaPuHuiTi_2_55_Regular;
      font-size: 20px;
      font-weight: normal;
      color: #666666;
    }
  }
  .right_setting {
    font-size: 20px;
  }
  .DataBoard_container_main {
    padding: 10px 20px 20px 20px;
    display: flex;
    flex-direction: row;
    // align-items: center;
    justify-content: space-between;
  }

  .DataBoard_container_main_statistics {
    display: flex;
    flex-direction: column;
    margin-top: 20px;
    .statistics_item {
      width: 223px;
      height: 100px;
      border-radius: 10px;
      margin-right: 20px;
      margin-bottom: 20px;
      .statistics_item_background1 {
        width: 100%;
        height: 30px;
      }
      .statistics_item_background {
        width: 100%;
        height: 80px;
        background: #FFFFFF;
        border-radius: 10px;
        box-shadow: 0px 4px 10px 0px rgba(43, 98, 203, 0.24);
      }
      .statistics_item_icon {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        background-color: rgba(255, 201, 201, 1);
        float: left;
        left: 20px;
        position: relative;
        font-size: 26px;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .statistics_item_number {
        float: right;
        right: 20px;
        position: relative;
        color: rgba(51, 51, 51, 1);
        font-size: 50px;
        height: 60px;
        line-height: 60px;
      }
      .statistics_item_name {
        float: right;
        right: 20px;
        position: relative;
        color: rgba(153, 153, 153, 1);
        font-size: 18px;
        top: -35px;
      }
    }

    .statistics_item:first-child {
      margin-left: 0px;
    }
  }

  .DataBoard_container_main_charts {
    width: calc(100% - 263px );
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .charts_item {
      width: calc(50% - 12px);
      background-color: white;
      height: 300px;
      margin-top: 20px;
      border-radius: 4px;
      box-shadow: 0px 4px 10px 0px rgba(43, 98, 203, 0.24);
    }
    .charts_item.double {
      width: 100%;
    }
  }
}
</style>
